<?

//require_once(dirname(__FILE__) . '/../abstract/htmail.php');

class bf_htmail_sock extends bf_htmail {

	protected $socket = null;

	protected function sendmail($to, $headers, $body) {

		if ($this->opts['localhost'] === null)
			$this->opts['localhost'] = bf::$inet->server_address();

		$nl = "\r\n";

		$errno = $errstr = '';
		$this->socket = fsockopen($this->opts['host'], $this->opts['port'], $errno, $errstr, $this->opts['timeout']);
		if (empty($this->socket))
			return -1;

		$response = fgets($this->socket, $this->opts['buffer-limit']);
		if ($this->opts['logging'] > 0)
			$this->log->append($response);
	
		$this->say("HELO {$this->opts['localhost']}{$nl}");

		if ($this->opts['login'] && $this->opts['password']) {

			$this->say("AUTH LOGIN{$nl}");
			$this->say(base64_encode($this->opts['login']) . $nl);
			$response = $this->say(base64_encode($this->opts['password']) . $nl);

			if (!preg_match('/^235/', $response))
				return -2;
		}

		$this->say("MAIL FROM: <{$this->opts['from']}>{$nl}");
		$this->say("RCPT TO: {$to}{$nl}");

		$this->say("DATA{$nl}");
		$response = $this->say("{$headers}{$nl}{$nl}{$body}{$nl}.{$nl}");
		if (!preg_match('/^250/', $response))
			return -3;

		$this->say("QUIT{$nl}");
		@fclose($this->socket);
		$this->socket = null;

		return 0;
	}

	private function say($what) {
		if ($this->opts['logging'] > 1)
			$this->log->append($what);
		fputs($this->socket, $what);
		$response = fgets($this->socket, $this->opts['buffer-limit']);
		if ($this->opts['logging'] > 0)
			$this->log->append($response);
		return $response;
	}
}

?>